# -*- coding: utf-8 -*-
# =============================================================================
#     FileName:
#         Desc:
#       Author:
#        Email:
#     HomePage:
#      Version:
#   LastChange:
#      History:
# =============================================================================
import heapq
import random


class TopMaxHeapItem(object):
    """
    TopMaxHeap中的元素
    """

    def __init__(self, item_key, item_data):
        self.item_key = item_key
        self.item_data = item_data

    def __cmp__(self, other):
        if self.item_key < other.item_key:
            return -1
        elif self.item_key > other.item_key:
            return 1
        else:
            return 0

    def __gt__(self, other):
        return self.item_key > other.item_key

    def __lt__(self, other):
        return self.item_key < other.item_key


class TopMaxHeap(object):
    """
    大定堆
    """

    def __init__(self, top_size):
        self._top_size = top_size
        self._item_heap = []

    def get_heap_size(self):
        """
        获取Heap长度
        :return:
        """
        return self._top_size

    def get_item_count(self):
        """
        获取当前Heap中元素个数
        :return:
        """
        return len(self._item_heap)

    def push_item(self, top_item: TopMaxHeapItem):
        """
        PUSH元素
        :param top_item:
        :return:
        """
        heapq.heappush(self._item_heap, top_item)
        if len(self._item_heap) > self._top_size:
            heapq.heappop(self._item_heap)

    def get_top_items(self):
        """
        获取所有元素并按照大小排序
        :return:
        """
        return [x for x in reversed([heapq.heappop(self._item_heap) for x in range(len(self._item_heap))])]

    def get_min_item(self):
        """
        获取Heap中最小的元素
        :return:
        """
        items = self.get_top_items()
        if len(items) > 0:
            return items[-1]
        return None

    def get_max_item(self):
        """
        获取Heap中最大的元素
        :return:
        """
        items = self.get_top_items()
        if len(items) > 0:
            return items[0]
        return None


def top_heap_test():
    """
    演示如何使用TopMaxHeap
    :return:
    """
    top_heap = TopMaxHeap(top_size=5)
    print("开始加载数据")
    for item_index in range(0, 20):
        item_key = random.randint(1, 1000)
        item_data = {"id": item_key, "data": item_key}
        print(item_data)
        top_item = TopMaxHeapItem(item_key=item_key, item_data=item_data)
        top_heap.push_item(top_item)
    top_items = top_heap.get_top_items()
    print("完成加载数据")
    print("TOP {}的数据：".format(top_heap.get_heap_size()))
    for top_item in top_items:
        print(top_item.item_data)


if __name__ == '__main__':
    top_heap_test()
